package com.valveinspectionsys.gridview;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.util.DateUtil;
import com.valveinspectionsys.util.FileNameUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;


/**
 * 图片涂鸦
 * 
 * @author king
 * 
 */
public class ScrawlActivity extends Activity {
    public static final int ITEM0 = Menu.FIRST;// 系统值
    private Paint mPaint = null;
    private LinearLayout linear = null;
    private TouchView touchView = null;
    public String classname;
    public String imgpath;
    private Button clearButton = null;
    private Button confirmButton = null;
    private Button cancelButton = null;
    private Button colorview = null;
    private Button[] colorButton = null;
    private Bitmap mbitmap = null;
    private final int colorcount = 7;
    private int COUNT = 0;
    private SeekBar mseekBar = null;
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private int[] colorArray = { Color.YELLOW, Color.BLACK, Color.WHITE, Color.GREEN, Color.GRAY, Color.RED, Color.BLUE };
    //提供了一种关于显示的通用信息，如显示大小，分辨率和字体
    DisplayMetrics dm = new DisplayMetrics();
    private String imapepath;// 图片位置
    private String olderImagePath;// 原图片位置
    int screenwidth = 0;
    int screenheight = 0;
    public boolean ismodify = false;
    public int i = 0;
    public String type="";//类型（0周期巡检 1临时巡检 2维修 3抢修）
    public String number;//编号
    public SharedPreferenceUtil sh;
    public String ntype="2";//0直线 1圆 2箭头 3折线 4折箭头
   
 
    @Override
    public void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.scrawl);
	sh=new SharedPreferenceUtil(this);
	classname = getIntent().getStringExtra("classname");
	imgpath = getIntent().getStringExtra("imgpath");
	type=getIntent().getStringExtra("type");
	number=getIntent().getStringExtra("number");
	
	//将取得的宽高维度存放于DisplayMetrics 对象中，而取得的宽高维度是以像素为单位(Pixel)，
	//“像素”所指的是“绝对像素”而非“相对像素”。 
	getWindowManager().getDefaultDisplay().getMetrics(dm);
	screenwidth = (int) (dm.widthPixels);
	screenheight = (int) (dm.heightPixels);
	confirmButton = (Button) findViewById(R.id.confirm);
	cancelButton = (Button) findViewById(R.id.cancel);
	clearButton = (Button) findViewById(R.id.clear);
	linear = (LinearLayout) findViewById(R.id.linear);
	
	colorButton = new Button[colorcount];
	int[] colorButtonID = { R.id.yellow, R.id.black, R.id.white, R.id.green, R.id.gray, R.id.red, R.id.blue };
	colorview = (Button) findViewById(R.id.color);
	colorview.setBackgroundColor(Color.GREEN);
	for (int i = 0; i < colorcount; i++) {
	    colorButton[i] = (Button) findViewById(colorButtonID[i]);
	    colorButton[i].setBackgroundColor(colorArray[i]);
	}

	mPaint = new Paint();
	mPaint.setAntiAlias(true);
	mPaint.setDither(true);
	mPaint.setColor(Color.GREEN);
	mPaint.setStyle(Paint.Style.STROKE);
	mPaint.setStrokeJoin(Paint.Join.ROUND);
	mPaint.setStrokeCap(Paint.Cap.ROUND);
	mPaint.setStrokeWidth(10);

	mseekBar = (SeekBar) findViewById(R.id.mseekBar);
	mseekBar.setMax(30);
	mseekBar.setProgress(10);
	for (int i = 0; i < colorcount; i++) {
	    colorButton[i].setOnClickListener(new View.OnClickListener() {
		private int colors = colorArray[COUNT];

		public void onClick(View v) {

		    mPaint.setColor(colors);
		    colorview.setBackgroundColor(colors);
		}
	    });
	    COUNT++;
	}
	mseekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
	    @Override
	    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }

	    @Override
	    public void onStartTrackingTouch(SeekBar seekBar) {
		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }

	    @Override
	    public void onStopTrackingTouch(SeekBar seekBar) {

		mPaint.setStrokeWidth(mseekBar.getProgress());
	    }
	});

	confirmButton.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View v) {
		Bitmap bitmap = touchView.mBitmap;
		FileOutputStream out = null;
		try {
		    out = new FileOutputStream(imapepath);	
		    //保存是将图片缩小两倍
//		    Matrix matrix = new Matrix(); 
//		     matrix.postScale(0.5f,0.5f); //长和宽放大缩小的比例			 
//		      bitmap= Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),matrix,true);	
		
		    boolean b = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		  
		    if (b) {
			Toast.makeText(ScrawlActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
		    } else {
			Toast.makeText(ScrawlActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
		    }
		   
		} catch (FileNotFoundException e) {
		    e.printStackTrace();
		}finally{
		    if(out!=null){
			try {
			    out.flush();
			    out.close();
			  
			} catch (IOException e) {
			   
			    e.printStackTrace();
			}
			
		    }
		}
	    }
	});
	cancelButton.setText("清除");
	cancelButton.setOnClickListener(new View.OnClickListener() {

	    public void onClick(View v) {
		init();
	    }
	});
	clearButton.setText("返回");
	clearButton.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View arg0) {

		if (classname.equals("OrderImageActivity")) {
		  
		} else if (classname.equals("GridMainActivity")) {
		    Intent intent;
		    intent = new Intent(ScrawlActivity.this, GridMainActivity.class);
		    intent.putExtra("imgpath", imapepath);
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_OK, intent);
		    finish();
		}
	    }
	});
	if (imgpath == null || imgpath.equals("")) {
	    System.out.println(i);
	    ismodify = false;
	    System.out.println("------------------------------拍照");
	    Photograph();
	    i++;
	} else {
	    imapepath = imgpath;
	    ismodify = true;
	    initImage(imapepath, true);
	    init();
	}

    }

    /**
     * 初始化
     */
    public void init() {	
	ntype="2";
	 linear.removeAllViews();
	touchView = new TouchView(this);
	linear.setPadding((screenwidth - touchView.mBitmap1.getWidth()) / 2, 0, (screenwidth - touchView.mBitmap1.getWidth()) / 2, 0);

	linear.addView(touchView);
    }

    public class TouchView extends View {

	private Bitmap mBitmap;
	private Bitmap mBitmap1;
	private Canvas mCanvas;
	private Path mPath;
	private Paint mBitmapPaint;
	private float startX, startY;
	private float endX,endY;
	
	

	private boolean b = false;

	public TouchView(Context c) {
	    
	    super(c);
	   
	    if (mbitmap == null) {
		return;
	    }
	   
	    mBitmap1 = mbitmap;
           
	   mBitmap = Bitmap.createBitmap(mBitmap1.getWidth(), mBitmap1.getHeight(), Config.ARGB_8888);
	    mCanvas = new Canvas(mBitmap);
	    mPath = new Path();
	    mBitmapPaint = new Paint(Paint.DITHER_FLAG);

	    mCanvas.drawBitmap(mBitmap1, 0, 0, mBitmapPaint);

	}

	@Override
	protected void onDraw(Canvas canvas) {
	    canvas.drawBitmap(mBitmap1, 0, 0, mBitmapPaint);

	    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

	    canvas.drawPath(mPath, mPaint);

	    // canvas.drawRect(50, 50, 180, 200, mBitmapPaint);

	}

	private float mX, mY;
	private static final float TOUCH_TOLERANCE = 10;
	/**
	 * 画一条直线
	 * 
	 * @param fromX
	 *            起点x坐标
	 * @param fromY
	 *            起点Y坐标
	 * @param toX
	 *            终点X坐标
	 * @param toY
	 *            终点Y坐标
	 */
	public void drawLine(float fromX, float fromY, float toX, float toY) {
	    Path linePath = new Path();
	    linePath.moveTo(fromX, fromY);
	    linePath.lineTo(toX, toY);
	    linePath.close();
	    mCanvas.drawPath(linePath, mPaint);
	    invalidate();
	}

	/**
	 * 画箭头
	 * 
	 * @param sx
	 * @param sy
	 * @param ex
	 * @param ey
	 */
	public void drawAL(Float sx, Float sy, Float ex, Float ey) {
	    double H = 12; // 箭头高度
	    double L = 5.25; // 底边的一半
	    int x3 = 0;
	    int y3 = 0;
	    int x4 = 0;
	    int y4 = 0;
	    double awrad = Math.atan(L / H); // 箭头角度
	    double arraow_len = Math.sqrt(L * L + H * H); // 箭头的长度
	    double[] arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow_len);
	    double[] arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow_len);
	    double x_3 = ex - arrXY_1[0]; // (x3,y3)是第一端点
	    double y_3 = ey - arrXY_1[1];
	    double x_4 = ex - arrXY_2[0]; // (x4,y4)是第二端点
	    double y_4 = ey - arrXY_2[1];
	    Double X3 = new Double(x_3);
	    x3 = X3.intValue();
	    Double Y3 = new Double(y_3);
	    y3 = Y3.intValue();
	    Double X4 = new Double(x_4);
	    x4 = X4.intValue();
	    Double Y4 = new Double(y_4);
	    y4 = Y4.intValue();
	    // 画线
	    mCanvas.drawLine(sx, sy, ex, ey, mPaint);
	    Path triangle = new Path();
	    triangle.moveTo(ex, ey);
	    triangle.lineTo(x3, y3);
	    triangle.lineTo(x4, y4);
	    triangle.close();
	    mCanvas.drawPath(triangle, mPaint);

	}

	private void touch_start(float x, float y) {
	    startX = x;
	    startY = y;
	    mPath.reset();
	    mPath.moveTo(x, y);
	    mX = x;
	    mY = y;
	}

	private void touch_move(float x, float y) {
//	    float dx = Math.abs(x - mX);
//	    float dy = Math.abs(y - mY);
//	    if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
//		mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
//		mX = x;
//		mY = y;
//	    }
	}

	private void touch_up(float x,float y) {
	 
	    if (ntype.equals("0")) {
		// mPath.lineTo(mX, mY);
		// mCanvas.drawPath(mPath, mPaint);
		drawLine(startX, startY, x, y);
	    } else if (ntype.equals("1")) {
		mCanvas.drawCircle((startX + x) / 2, (startY + y) / 2, (float) Math.abs(Math.sqrt((x - startX) * (x - startX) + (y - startY) * (y - startY))) / 2, mPaint);
		// RectF rf2 = new RectF(startX, startY, x, y);
		//
		// mCanvas.drawOval(rf2, mPaint);

	    } else if (ntype.equals("2")) {
		drawAL(startX, startY, x, y);
	    } else if(ntype.equals("3")){
		drawLine(endX, endY, x, y);
	    }else if(ntype.equals("4")){
		drawAL(endX, endY, x, y);
	    }
	    endX=x;
	    endY=y;
	    mPath.reset();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
	    float x = event.getX();
	    float y = event.getY();

	    switch (event.getAction()) {
	    case MotionEvent.ACTION_DOWN:
		touch_start(x, y);
		invalidate();
		break;
	    case MotionEvent.ACTION_MOVE:
		touch_move(x, y);
		invalidate();
		break;
	    case MotionEvent.ACTION_UP:
		touch_up(x,y);
		invalidate();
		break;
	    }
	    return true;
	}

	public Bitmap getmBitmap() {
	    return mBitmap;
	}

	public void setmBitmap(Bitmap mBitmap) {
	    this.mBitmap = mBitmap;
	}

	public Bitmap getmBitmap1() {
	    return mBitmap1;
	}

	public void setmBitmap1(Bitmap mBitmap1) {
	    this.mBitmap1 = mBitmap1;
	}

	public void destroy(){
	
	    if(this.mBitmap!=null){
		this.mBitmap.recycle();
	    }
	}
    }

    // 计算
    public double[] rotateVec(Float px, Float py, double ang, boolean isChLen, double newLen) {
	double mathstr[] = new double[2];
	// 矢量旋转函数，参数含义分别是x分量、y分量、旋转角、是否改变长度、新长度
	double vx = px * Math.cos(ang) - py * Math.sin(ang);
	double vy = px * Math.sin(ang) + py * Math.cos(ang);
	if (isChLen) {
	    double d = Math.sqrt(vx * vx + vy * vy);
	    vx = vx / d * newLen;
	    vy = vy / d * newLen;
	    mathstr[0] = vx;
	    mathstr[1] = vy;
	}
	return mathstr;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {

	    if (resultCode == RESULT_OK) {

		initImage(imapepath, false);

	    } else if (resultCode == RESULT_CANCELED) {
                    
		if (classname.equals("OrderImageActivity")) {
		 

		} else if (classname.equals("GridMainActivity")) {
		    Intent intent;
		    intent = new Intent(this, GridMainActivity.class);
		    intent.putExtra("imgpath", "");
		    intent.putExtra("ismodify", ismodify);
		    setResult(RESULT_CANCELED, intent);
		}
		finish();
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 拍照
     */
    public void Photograph() {

	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	FileNameUtil f = new FileNameUtil();	
	if(type.equals("1")){
	    imapepath=f.SDCardPath("DaoHang/"+number);
	}else{
	    imapepath=f.SDCardPath("DaoHang/"+number);
	}
	if (imapepath == null) {
	    Toast.makeText(ScrawlActivity.this, "SD卡不可用", Toast.LENGTH_LONG).show();
	    return;
	}
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
	imapepath = imapepath + "/" +sh.getValue(XmlNameHelper.userID)+ fileName;
	olderImagePath = imapepath;

	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imapepath)));
	
	startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);

    }

    /**
     * 初始化照片
     * 
     * @param imagepath
     * @throws IOException
     */
    public void initImage(String imagepath, boolean b) {

	FileInputStream fis = null;
	try {
	    fis = new FileInputStream(imagepath);

	    FileDescriptor fd = fis.getFD();
	    
	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeFileDescriptor(fd, null, options);
	    int outWidth = Math.round(options.outWidth/800);
	    int outHeight =Math.round( options.outHeight/600);
	  
	     if(outWidth>1&&outHeight>1){
		 if(outHeight>=outWidth){
		     options.inSampleSize=outWidth;
		 }else{
		     options.inSampleSize=outHeight;
		 }
	     }
	    if (b) {
		options.inSampleSize = 1;
	    }
	    File f=new File(imagepath);
	    int degree =	    readPictureDegree( f.getAbsolutePath());
	 
	    options.inJustDecodeBounds = false;
	    mbitmap = BitmapFactory.decodeStream(fis, null, options);	
	 
	    if (!b) {
		//无法 解释为什么当旋转角度为0是会报错，必须要用Copy方法
	        if(degree==0){
	            mbitmap=mbitmap.copy(Bitmap.Config.ARGB_8888, true);
	        }else{	           
	            Matrix matrix = new Matrix();
		     matrix.reset();
		//设置图片旋转角度
		     matrix.postRotate(degree);
			// 创建新的图片			
		      mbitmap = Bitmap.createBitmap(mbitmap, 0, 0, mbitmap.getWidth(), mbitmap.getHeight(), matrix, true);			 
	        }
		Canvas canvas = new Canvas(mbitmap);
		TextPaint paint = new TextPaint();
		 paint.setTextSize(20f);
		 paint.setColor(Color.RED);
		 canvas.drawText(DateUtil.getNowDate(), mbitmap.getWidth()-190, 30f, paint);
		 canvas.save();		 
		FileOutputStream out = new FileOutputStream(imapepath);
		mbitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		out.flush();
		out.close();
		fis.close();				
	    }
	  //保存后再将图片放大2*2倍展现
//		 Matrix matrix = new Matrix(); 
//		  matrix.postScale(2,2); //长和宽放大缩小的比例		
//		 mbitmap= Bitmap.createBitmap(mbitmap,0,0,mbitmap.getWidth(),mbitmap.getHeight(),matrix,true);
	    init();
	} catch (FileNotFoundException e) {
	    System.out.println("FileNotFoundException");
	    e.printStackTrace();
	} catch (IOException e) {
	    System.out.println("IOException");
	    e.printStackTrace();
	}

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
	if (keyCode == KeyEvent.KEYCODE_BACK) {	 
		Intent intent;
		intent = new Intent();
		intent.putExtra("imgpath", imapepath);
		intent.putExtra("ismodify", ismodify);
		setResult(RESULT_OK, intent);	    
	}
	return super.onKeyDown(keyCode, event);
    }

    /**
     * 读取图片属性：旋转的角度
     * 
     * @param path
     *            图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
	int degree = 0;
	try {
	    ExifInterface exifInterface = new ExifInterface(path);
	    int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
	    switch (orientation) {
	    case ExifInterface.ORIENTATION_ROTATE_90:
		degree = 90;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_180:
		degree = 180;
		break;
	    case ExifInterface.ORIENTATION_ROTATE_270:
		degree = 270;
		break;
	    }
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return degree;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

	menu.add(0, ITEM0, 0, "直线");
	menu.add(0, ITEM0 + 1, 0, "圆");
	menu.add(0, ITEM0 + 2, 0, "直箭头");
	menu.add(0, ITEM0 + 3, 0, "折线");
	menu.add(0, ITEM0 + 4, 0, "折箭头");
        
	menu.findItem(ITEM0 + 1);
	// 获取MenuInflater对象
	// setMenuBackGround();
	return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	if (item.getItemId() == ITEM0) {
	 
	    ntype = "0";
	    System.out.println("------onOptionsItemSelected-------"+ntype);
	} else if (item.getItemId() == ITEM0 + 1) {
	    
	    ntype = "1";
	    System.out.println("------onOptionsItemSelected-------"+ntype);
	} else if (item.getItemId() == ITEM0 + 2) {
	    
	    ntype = "2";
	    System.out.println("------onOptionsItemSelected-------"+ntype);
	}else if(item.getItemId()==ITEM0+3){
	    if(ntype.equals("0")||ntype.equals("3")){		
		 ntype="3";
	    }else{
		Toast.makeText(ScrawlActivity.this, "请先画直线", Toast.LENGTH_SHORT).show();
		ntype="0";
	    }
  
	}else if(item.getItemId()==ITEM0+4){
	    if(ntype.equals("0")||ntype.equals("3")){
		
		  ntype="4";
	    }else{
		Toast.makeText(ScrawlActivity.this, "请先画直线", Toast.LENGTH_SHORT).show();
		ntype="0";
	    }
	  
	    System.out.println("------onOptionsItemSelected-------"+ntype);
	}
	return super.onOptionsItemSelected(item);
    }
    @Override
    protected void onDestroy() {
 
	if (mbitmap != null) {
	    mbitmap.recycle();
	}
	
	
	super.onDestroy();
    }
    
}